package com.jianying.day08;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink01_KeyedState_ValueState_1
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/9 09:40
 * @Version: 1.0
 */
public class Flink07_KeyedState_TTL {
    public static void main(String[] args) throws Exception {
        // TODO 状态失效时间（统计相邻两个水位值相差>10）
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> mapDS = env.socketTextStream("localhost", 8888)
                .map(new WaterSensorMapFunction());

        // TODO 按键分组 ID
        KeyedStream<WaterSensor, String> keyByDS = mapDS.keyBy(WaterSensor::getId);

        // TODO 分组后数据处理
        keyByDS.process(
                new KeyedProcessFunction<String, WaterSensor, String>() {
                    // TODO 定义一个值状态，存放上次水位值
                    ValueState<Integer> lastVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<Integer> valueStateDescriptor = new ValueStateDescriptor<Integer>("lastVcState", Integer.class);
                        // TODO TTL 生存时间是处理时间
                        valueStateDescriptor.enableTimeToLive(
                                StateTtlConfig
                                        .newBuilder(Time.seconds(10))
                                        // .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                        .build()
                        );
                        lastVcState = getRuntimeContext().getState(valueStateDescriptor);

                    }

                    @Override
                    public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                        Integer lastVc = lastVcState.value() == null ? 0 : lastVcState.value();
                        Integer curVc = value.getVc();
                        String id = ctx.getCurrentKey();

                        if(Math.abs(curVc - lastVc) > 10) {
                            out.collect("传感器:" + id + "，当前水位值：" + curVc + ",上一次水位值：" + lastVc + "差大于10");
                        }

                        lastVcState.update(curVc);

                    }
                }
        ).printToErr();

        env.execute();
    }
}
